package com.company.learnjpa.config;

import com.company.learnjpa.model.entity.Role;
import com.company.learnjpa.model.entity.User;
import com.company.learnjpa.model.repository.UserRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.security.enterprise.credential.Credential;
import jakarta.security.enterprise.credential.UsernamePasswordCredential;
import jakarta.security.enterprise.identitystore.CredentialValidationResult;
import jakarta.security.enterprise.identitystore.IdentityStore;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author xiaolei
 */
@Named(value = "customDatabaseIdentityStore")
@ApplicationScoped
public class CustomDatabaseIdentityStore implements IdentityStore {

    @Inject
    private UserRepository userRepository;

    @Override
    public CredentialValidationResult validate(Credential credential) {
        System.out.println("=====>" + credential);
        UsernamePasswordCredential upc = (UsernamePasswordCredential) credential;
        String username = upc.getCaller();
        String password = upc.getPasswordAsString();

        User user = userRepository.findOneByFields(Map.of("username", username));
        if (user == null) {
            return CredentialValidationResult.INVALID_RESULT; // 用户名不存在
        }

        if (!Objects.equals(user.getPassword(), password)) {
            return CredentialValidationResult.INVALID_RESULT; // 密码错误
        }

        // 获取角色
        Set<String> roleNameSet = new HashSet<>();
        for (Role role : user.getRoleList()) {
            roleNameSet.add(role.getName());
        }

        return new CredentialValidationResult(username, roleNameSet);
    }

}
